<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>支付页</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
  <link rel="stylesheet" type="text/css" href="./css/top-nav-optimized.css"/>
  <script src="https://cdn.tailwindcss.com"></script>

  <!-- 配置Tailwind自定义颜色和字体 -->
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#1677ff',
            secondary: '#ff7d00',
            success: '#52c41a',
            danger: '#ff4d4f',
            neutral: '#f5f5f5',
            'neutral-dark': '#434343'
          },
          fontFamily: {
            inter: ['Inter', 'system-ui', 'sans-serif'],
          },
        },
      }
    }
  </script>

  <style type="text/tailwindcss">
    @layer utilities {
      .content-auto {
        content-visibility: auto;
      }
      .card-shadow {
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
      }
      .transition-custom {
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      }
      .input-focus {
        @apply focus:ring-2 focus:ring-primary/50 focus:border-primary focus:outline-none;
      }
    }
    .input-focus:focus {
      outline: none; /* 清除默认获焦外边框 */
      border-color: #6366f1; /* 获焦时边框改为紫色（可自定义颜色） */
      box-shadow: 0 0 0 2px rgba(99, 102, 241, 0.2); /* 柔和阴影，增强获焦反馈 */
    }
  </style>
</head>

<body class="font-inter bg-gray-50 text-neutral-dark">
<!--head-->
<div id="payApp" class="min-h-screen flex flex-col">
  <top class="bg-white shadow-sm"></top>
  <div class="cart py-container flex-grow">
    <!--logoArea-->
    <div class="logoArea py-6 px-4 md:px-8 flex items-center">
      <a href="/" class="flex items-center">
        <div class="logo mr-3">
          <img src="./img/-alogo.png" alt="网站Logo" class="h-10 w-auto object-contain">
        </div>
        <span class="text-xl font-semibold text-neutral-dark">收银台</span>
      </a>
    </div>

    <!--主内容-->
    <div class="checkout py-container pay max-w-4xl mx-auto px-4 md:px-8 mb-12">
      <!-- 订单信息卡片 -->
      <div class="bg-white rounded-xl p-6 card-shadow mb-6">
        <div class="checkout-tit flex flex-col md:flex-row justify-between items-start md:items-center">
          <h4 class="tit-txt flex items-start mb-4 md:mb-0">
            <span class="success-icon text-success mr-2 mt-1">
              <i class="fas fa-check-circle text-xl"></i>
            </span>
            <span class="success-info">
              订单提交成功，订单号：{{order.id}}。请您及时付款，订单将在
              <span class="text-danger font-medium">{{remainTime}}</span> 后取消。
            </span>
          </h4>
          <span class="sui-lead flex items-center">
            <em class="mr-2">应付金额：</em>
            <em class="orange money text-2xl font-bold text-danger">￥{{util.formatPrice(order.totalFee)}}</em>
            <em class="ml-1">元</em>
          </span>
        </div>
      </div>

      <!-- 支付方式选择 -->
      <div class="checkout-steps bg-white rounded-xl overflow-hidden card-shadow">
        <div class="container">
          <div class="tab-wrapper">
            <!-- 支付方式选项卡 -->
            <div class="flex flex-wrap p-4 border-b border-gray-100">
              <!-- 支付宝支付 -->
              <div class="w-full md:w-auto flex-1 md:flex-none">
                <input type="radio" name="tab-radio" v-model="tab" :value="1"
                       class="tab-radio sr-only" id="tab-radio-1">
                <label for="tab-radio-1"
                       class="tab-handler tab-handler-1 block w-full md:w-40 py-3 px-4 text-center rounded-lg transition-custom cursor-pointer
                              hover:bg-gray-50 flex items-center justify-center space-x-2
                              font-medium"
                       :class='{"tab-selected bg-primary/10 text-primary border-b-2 border-primary": tab === 1, "text-gray-600": tab !== 1}'>
                  <i class="fab fa-alipay text-xl"></i>
                  <span>支付宝支付</span>
                </label>
              </div>

              <!-- 微信支付 -->
              <div class="w-full md:w-auto flex-1 md:flex-none">
                <input type="radio" name="tab-radio" v-model="tab" :value="2"
                       class="tab-radio sr-only" id="tab-radio-2">
                <label for="tab-radio-2"
                       class="tab-handler tab-handler-2 block w-full md:w-40 py-3 px-4 text-center rounded-lg transition-custom cursor-pointer
                              hover:bg-gray-50 flex items-center justify-center space-x-2
                              font-medium"
                       :class='{"tab-selected bg-success/10 text-success border-b-2 border-success": tab === 2, "text-gray-600": tab !== 2}'>
                  <i class="fab fa-weixin text-xl"></i>
                  <span>微信支付</span>
                </label>
              </div>

              <!-- 余额支付 -->
              <div class="w-full md:w-auto flex-1 md:flex-none">
                <input type="radio" name="tab-radio" v-model="tab" :value="3"
                       class="tab-radio sr-only" id="tab-radio-3">
                <label for="tab-radio-3"
                       class="tab-handler tab-handler-3 block w-full md:w-40 py-3 px-4 text-center rounded-lg transition-custom cursor-pointer
                              hover:bg-gray-50 flex items-center justify-center space-x-2
                              font-medium"
                       :class='{"tab-selected bg-secondary/10 text-secondary border-b-2 border-secondary": tab === 3, "text-gray-600": tab !== 3}'>
                  <i class="fas fa-wallet text-xl"></i>
                  <span>余额支付</span>
                </label>
              </div>
            </div>

            <!-- 支付内容区域 -->
            <div class="tab-content p-6" v-show="tab === 1 || tab === 2">
              <div class="flex flex-col items-center py-8">
                <div class="code bg-white p-4 rounded-lg border border-gray-100 mb-6 shadow-sm">
                  <div id="qrImage2" class="flex justify-center">
                    <img src="./img/erweima.png" alt="支付二维码" class="w-64 h-64 object-contain">
                  </div>
                </div>
                <div class="saosao text-center">
                  <div class="flex items-center justify-center mb-2">
                    <i v-if="tab === 1" class="fab fa-alipay text-primary text-2xl mr-2"></i>
                    <i v-if="tab === 2" class="fab fa-weixin text-success text-2xl mr-2"></i>
                    <p class="text-lg font-medium">{{paymentTypes[tab - 1].label}}扫一扫</p>
                  </div>
                  <p class="text-gray-500">扫描二维码完成支付</p>
                  <div class="mt-6 pt-6 border-t border-gray-100">
                    <p class="text-gray-500 text-sm">
                      <i class="fas fa-info-circle mr-1 text-primary"></i>
                      请在{{remainTime}}内完成支付，超时后订单将自动取消
                    </p>
                  </div>
                </div>
              </div>
            </div>

            <!-- 余额支付内容 -->
            <div class="tab-content p-6" v-show="tab === 3">
              <div class="max-w-md mx-auto py-6">
                <div class="mb-8">
                  <label for="payPassword" class="block text-gray-700 mb-2 font-medium">请输入支付密码：</label>
                  <div class="relative">
                    <!-- 输入框：type 动态绑定（根据 showPwd 变量切换） -->
                    <input
                            id="payPassword"
                            :type="showPwd ? 'text' : 'password'"
                    v-model="password"
                    class="w-full px-4 py-3 rounded-lg border border-gray-300 input-focus text-lg"
                    placeholder="请输入支付密码"
                    maxlength="6"
                    >
                    <!-- 图标：动态切换（眼睛/闭眼），点击触发 showPwd 反转 -->
                    <i
                            :class="['fas', showPwd ? 'fa-eye-slash' : 'fa-eye', 'absolute', 'right-3', 'top-1/2', '-translate-y-1/2', 'text-gray-400', 'cursor-pointer', 'hover:text-gray-600']"
                            @click="showPwd = !showPwd"
                    ></i>
                  </div>
                  <p class="text-gray-500 text-sm mt-2">
                    <i class="fas fa-shield-alt mr-1"></i>
                    请输入您的数字支付密码
                  </p>
                </div>

                <button @click="payByBalance"
                        class="w-full bg-secondary hover:bg-secondary/90 text-white font-medium py-3 px-6 rounded-lg transition-custom flex items-center justify-center space-x-2 shadow-md hover:shadow-lg">
                  <i class="fas fa-lock"></i>
                  <span>确认支付 ￥{{util.formatPrice(order.totalFee)}}元</span>
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 支付帮助信息 -->
      <div class="mt-6 bg-white rounded-xl p-5 card-shadow">
        <h3 class="text-lg font-semibold mb-3 flex items-center">
          <i class="fas fa-question-circle text-primary mr-2"></i>
          支付帮助
        </h3>
        <ul class="text-gray-600 space-y-2 text-sm">
          <li class="flex items-start">
            <i class="fas fa-check text-success mt-1 mr-2"></i>
            <span>支付成功后，系统将自动跳转到支付成功页面</span>
          </li>
          <li class="flex items-start">
            <i class="fas fa-check text-success mt-1 mr-2"></i>
            <span>如果您已支付但未跳转，请点击页面刷新按钮尝试刷新</span>
          </li>
          <li class="flex items-start">
            <i class="fas fa-check text-success mt-1 mr-2"></i>
            <span>订单将在{{remainTime}}后自动取消，请及时完成支付</span>
          </li>
        </ul>
      </div>
    </div>
  </div>

  <!-- 页脚 -->
  <footer class="bg-white border-t border-gray-200 py-6">
    <div class="max-w-4xl mx-auto px-4 text-center text-gray-500 text-sm">
      <p>© 2025 支付平台 版权所有</p>
      <p class="mt-2">客服热线：123-123-123（工作时间：9:00-21:00）</p>
    </div>
  </footer>
</div>

<script src="./js/vue.js"></script>
<script src="./js/axios.min.js"></script>
<script src="js/common.js"></script>
<script src="js/top.js"></script>
<script src="js/qrcode.min.js"></script>
<script>
  let app = new Vue({
    el: "#payApp",
    data() {
      return {
        util, // 工具类
        order: {id: 458010519, totalFee: 298400, paymentType: 3}, // 订单信息
        paymentTypes: [{value: "aliPay", label: "支付宝"}, {value: "wxPay", label: "微信"}, {value: "balance", label: "余额"}], // 支付方式
        tab: 3, // 标签页
        password: "", // 支付密码
        remainTime: "",
        user: null,
        payOrderNo: "", // 支付单号
        showPwd: false // 控制密码是否可见（默认隐藏）
      }
    },
    created() {
      util.store.set("return-url", location.href);
      this.user = util.store.get("user-info")
      // 查询订单
      axios.get("/orders/" + util.getUrlParam("id"))
              .then(resp => {
                // 查询到订单了
                this.order = resp;
                this.tab = this.order.paymentType;
                // 创建支付单
                this.createPayOrder(this.order.id);
                // 设置倒计时
                const deadLine = new Date(this.order.createTime).getTime() + 1800000;
                const tid = setInterval(() => {
                  const remainTime = deadLine - new Date().getTime();
                  this.remainTime = Math.floor(remainTime / 60000) + "分" + Math.floor((remainTime % 60000) / 1000) + "秒";
                })
                setTimeout(() => {
                  // 清除倒计时
                  clearInterval(tid)
                  // 跳转到失败页
                  alert("支付超时！");
                }, deadLine - new Date().getTime())
              })
              .catch(err => console.log(err));
    },
    watch: {
      tab(val) {
        // 创建支付单
        this.createPayOrder(this.order.id);
      }
    },
    methods: {
      createPayOrder(id) {
        axios.post("/pay-orders",
                {
                  bizOrderNo: this.order.id,
                  amount: this.order.totalFee,
                  payType: this.tab === 3 ? 5 : 4,
                  orderInfo: "电商平台商品",
                  payChannelCode: this.paymentTypes[this.tab - 1].value
                },
                {
                  transformResponse: data => data
                }
        ).then(resp => {
          // 判断支付方式
          if (this.tab === 3) {
            // 余额支付，保存交易单号即可
            this.payOrderNo = resp;
            return;
          }
          // 扫描支付，生成二维码
          new QRCode(document.getElementById("qrImage"), {
            text: resp,
            width: 250,
            height: 250,
            colorDark: "#000000",
            colorLight: "#ffffff",
            correctLevel: QRCode.CorrectLevel.H
          });
          // 开启定时任务，查询付款状态
          const taskId = setInterval(() => {
            this.queryOrderStatus(taskId);
          }, 3000);
          // 同时设置一个定时任务，5分钟后，去微信主动查询支付结果，如果依然失败，终止查询，认为付款失败
          setTimeout(() => {
            // 清除之前的定时任务
            clearInterval(taskId);
            // 主动查询支付状态
            this.queryPayStatus();
          }, 300000)
        })
                .catch(err => console.log(err));
      },
      queryOrderStatus(taskId) {
        axios.get("/order/status/" + id)
                .then(resp => {
                  let i = resp;
                  if (i === 5) {
                    // 付款失败
                    clearInterval(taskId);
                    // 跳转到付款失败页
                    alert("支付失败，请重试！")
                  } else if (i !== 1) {
                    // 付款成功
                    clearInterval(taskId);
                    // 跳转到付款成功页
                    location.href = "/paysuccess.html?orderId=" + id;
                  }
                }).catch((e) => {
          alert("支付状态查询失败，请刷新页面重试。");
          clearInterval(taskId);
        })
      },
      queryPayStatus() {
        axios.get("/pay/status/" + id)
                .then(resp => {
                  // resp是返回的状态，1代表未支付、2代表已支付、3代表支付失败、4正在支付
                  if (resp !== 2) {
                    // 未支付或者支付失败，跳转到失败页
                    alert("支付失败，请重试！")
                  }
                  // 已经支付，跳转到支付成功页面
                  location.href = "/paysuccess.html?orderId=" + id;
                })
                .catch(err => {
                  console.log(err)
                  alert("支付失败，请重试！")
                })
      },
      payByBalance() {
        if(!this.payOrderNo){
          alert("交易单号为空")
          return;
        }
        axios.post("/pay-orders/" + this.payOrderNo,
                {id: this.payOrderNo, pw: this.password},{
                  transformResponse: data => data
                })
                .then(() => {
                  // 已经支付，跳转到支付成功页面
                  location.href = "/paysuccess.html?orderId=" + this.order.id;
                })
                .catch(err => {
                  console.log(err)
                  alert("支付失败，请重试！")
                })
      }
    }
  });
</script>
</body>

</html>
